//
//  FYStatusDAL.swift
//  Mircore
//
//  Created by apple on 16/8/21.
//  Copyright © 2016年 飞羽. All rights reserved.
//

import UIKit

//最后删除缓存时间

let  MaxTimeInterval: NSTimeInterval = -7 * 24 * 60 * 60

//数据库访问层  用于缓存微博数据及加载网络请求的微博数据

class FYStatusDAL: NSObject {
//处理微博首页数据缓存逻辑
    
    class  func  loadData(maxID: Int64, sinceID: Int64, callBack: (statusDicArray: [[String: AnyObject]]) -> ()) {
    
    
       //处理本地是否有缓存数据
        
        let  result  =  checkCacheData(maxID, sinceID: sinceID)
        
        //如果本地有缓存数据直接返回缓存数据
        
        if  result.count > 0 {
        
         callBack(statusDicArray: result)
            
           return
        }
        
        //如果本地没有缓存数据那么去网络请求微博数据
        
        CZNetworkTools.sharedTools.requestStatuses(FYUserAccountViewModel.sharedUserAccount.accessToken!, maxId: maxID, sinceId: sinceID) { (response, error) in
            
            if  error != nil {
            
            callBack(statusDicArray: result)
                
                return
            }
            
            //代码执行到此 表情网络请求成功
            
            guard  let  dic  = response  as?  [String: AnyObject]  else {
            
            callBack(statusDicArray: result)
            
                return
            }
            
            //字典格式正确
            
            guard  let  dicArray  = dic["statuses"]  as? [[String: AnyObject]]  else {
            
            callBack(statusDicArray: result)
                
                return
            
            }
            
            //缓存微博数据
            
            FYStatusDAL.cacheData(dicArray)
            
            //缓存到本地成功后返回网络请求的数据
            
            callBack(statusDicArray: dicArray)
        
        }
        
    }
    
     //查询本地缓存数据
    
    class func  checkCacheData(maxID: Int64, sinceID: Int64) -> [[String: AnyObject]] {
        
        //准备sql
        
     var  sql  = "SELECT * FROM statuses\n"
        
        if  maxID > 0 {
        
        //上拉加载
            
            sql += "where statusid < \(maxID)\n"
        }else  {
        
            //下拉刷新
            
            sql  += "where statusid > \(sinceID)\n"
        
        }
        
        //拼接userid
        
        sql += "and userid = \(FYUserAccountViewModel.sharedUserAccount.userAccount?.uid)\n"
        
        //排序方式
        
        sql  += "order by statusid desc\n"
        
        //最大获取数量
        
        sql  += "limit 20\n"
        
        let  result  = SqliteManager.sharedManager.queryDicArrayForSql(sql)
        
        var  tempArray  = [[String: AnyObject]]()
        
        
        for  value  in  result {
        
            //获取微博二进制数据
            
            let  statusData = value["status"]! as! NSData
            
            //通过微博二进制数据转成微博字典
            
            let  statusDic =  try!  NSJSONSerialization.JSONObjectWithData(statusData, options: [])  as! [String: AnyObject]
            
            tempArray.append(statusDic)
        
        
        }
        
         return tempArray
 }


//缓存微博数据

    class  func   cacheData(statusDicArray:[[String: AnyObject]])  {

   //准备sql
        
        let  sql  = "INSERT OR Replace INTO statuses (statusid, status, userid) VALUES (?, ?, ?)"

         //用户id
        
        let  userid = FYUserAccountViewModel.sharedUserAccount.userAccount?.uid
        
        //执行sql语句
        
        SqliteManager.sharedManager.queue.inTransaction { (db, rollBack) in
            
            //遍历微博字典数组插入数据
            
            for  statusDic  in  statusDicArray  {
            
            //微博id
                
            let  id  = statusDic["id"]!
                
                //微博内容
                
                let  statusDicData  = try!  NSJSONSerialization.dataWithJSONObject(statusDic, options: [])
            
            
                let  result  = db.executeUpdate(sql, withArgumentsInArray: [id, statusDicData, "\(userid)"])
                
                if  result  == false  {
                
                    
                    //如果出现异常让事务回滚
                    
                    rollBack.memory = true
                    
                    break
                
                }
            }
        }
 }


//清除缓存数据

    class  func  clearCacheData() {

   let  date = NSDate().dateByAddingTimeInterval(MaxTimeInterval)
        
        let  dt = NSDateFormatter()
        
        dt.dateFormat  = "yyyy-MM-dd  HH:mm:ss"
        
        dt.locale  = NSLocale(localeIdentifier: "en_US")
        
        //获取时间字符串
        
        let  dtStr = dt.stringFromDate(date)
        
        //准备sql
        
        let  sql = "Delete FROM statuses where time < '\(dtStr)"
        
        //执行sql语句
        
        SqliteManager.sharedManager.queue.inDatabase { (db) in
            
            let  result  = db.executeUpdate(sql, withArgumentsInArray: nil)
            
            if  result {
            
             print("删除数据成功,影响了\(db.changes())条数据")
            }else  {
            
             print("删除数据失败")
            }
        }
 }

}